package cn.edu.scau.cmi.wujiaming.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.wujiaming.hibernate.domain.Student;
import cn.edu.scau.cmi.wujiaming.hibernate.hibernateUtil.HibernateUtil;

public class StudentDAO{
	
	public  static boolean save(Student  student) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query<Student>  query  = session.createQuery("from Student where name = \'" + student.getName() +"\'");
		Student existedStudent = query.uniqueResult();
		if(existedStudent != null) {
			transaction.commit();
			session.close();
			return  false;
		}
		session.save(student);
		transaction.commit();
		session.close();
		return true;
	}
	
	public static void delete(Student  student) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		session.delete("Student",student);
		transaction.commit();
		session.close();
	}
	
	public static Student findStudentByName(String name) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query<Student>  query  = session.createQuery("from Student where name = \'" + name +"\'");
		Student student = query.uniqueResult();
		transaction.commit();
		session.close();
		return student;
	}
	
	
	
	
	public static Student  update(Student  student) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		session.saveOrUpdate(student);
		transaction.commit();
		session.close();
		return student;
	}
	
	public static List<Student>  findAllStudent(){
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query  query  = session.createQuery("from Student");
		List<Student> students = query.getResultList();
		transaction.commit();
		session.close();
		return students;
	}
	
}
